// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config_cmd

import (
	"fmt"
	"os"
	"syscall"

	"gitcode.com/openseaotter/so_agent/config"
	"gitcode.com/openseaotter/so_agent/utils"
	"github.com/spf13/cobra"
)

var removeWatchCmd = &cobra.Command{
	Use: "removeWatch",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 0 {
			return fmt.Errorf("need param [watch id]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		watchId := args[0]

		cfg, err := config.ReadAgentConfig()
		if err != nil {
			return err
		}
		newWatchCfgList := []config.WatchConfig{}

		for _, watchCfg := range cfg.WatchCfgList {
			if watchCfg.WatchId != watchId {
				newWatchCfgList = append(newWatchCfgList, watchCfg)
			}
		}
		cfg.WatchCfgList = newWatchCfgList

		err = config.WriteAgentConfig(cfg)
		if err != nil {
			return err
		}
		fmt.Println("remove watch cfg success")

		pid, err := utils.LoadPid()
		if err == nil {
			p, err := os.FindProcess(pid)
			if err == nil {
				p.Signal(syscall.SIGHUP)
				fmt.Println("send SIGHUP to process")
			}
		}

		return nil
	},
}
